<template>
  <el-form class="login-container" label-position="left" :model="loginForm" :rules="rules"
           label-width="0px">
    <h3 class="login_title">{{type['part']}} {{type['name']}}注册</h3>
    <el-form-item prop="username">
      <el-input type="text" v-model="loginForm.username"
                auto-complete="off" placeholder="账号（必填）"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password"
                auto-complete="off" placeholder="密码（必填）"></el-input>
    </el-form-item>
    <el-form-item prop="avatar" class="avatar">
      <input id="a1" type="file" ref="avatar" @change="uploadAvatar" hidden>
      <img :src="loginForm.avatar.url">
      <label for="a1">
        <div>上传头像（非必填）</div>
      </label>
    </el-form-item>
    <el-form-item prop="nickname">
      <el-input type="text" v-model="loginForm.nickname"
                auto-complete="off" placeholder="昵称（非必填）"></el-input>
    </el-form-item>
    <el-form-item prop="summary">
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入个人简介（非必填）"
        v-model="loginForm.summary">
      </el-input>
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button type="primary" style="width: 100%; " v-on:click="register" plain>注册</el-button>
    </el-form-item>
    <div class="back" @click="$router.push('/userLogin')">返回登录</div>
  </el-form>
</template>

<script>
import ossUpload from "../../utils/ossUpload";
export default {
  name: "register_page",
  data () {
    return {
      loginForm: {
        username: '',
        password: '',
        nickname: '',
        summary: '',
        avatar : {
          default:require("../../assets/images/addAvatar.png"),
          url: require("../../assets/images/addAvatar.png"),
          file: ''
        },
        avatarFile:null,
        avatarUrl:""
      },
      rules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ]
      },
      responseResult: []
    }
  },
  beforeMount() {
    window.localStorage.setItem("avatar", this.loginForm.avatar.default);
  },
  props:['type'],
  methods: {
    uploadAvatar() {
      const file = this.$refs.avatar.files[0];
      let url = null ;
      if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
      }else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
      }else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      }
      console.log(url);
      this.loginForm.avatar.url = url;
      this.loginForm.avatar.file = file;
      window.localStorage.setItem("avatar",url);
    },
    async getOssPicture() {
      const self = this;
      let file = this.loginForm.avatar.file;
      let avatarUrl = "";
      // 上传部分
      let data = new FormData();
      data.append('file', file);
      this.$axios({
        url:'/oss',
        method: 'post',
        data,
        headers: {},
        //原生获取上传进度的事件
        onUploadProgress: function(progressEvent) {
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
          console.log('上传 ' + complete)
        }
      }).then(res => {
        var jsonString = JSON.stringify(res.data);
        var jsonObj = JSON.parse(jsonString);
        avatarUrl = jsonObj.data.url;
        alert(jsonObj.data.url);
        self.loginForm.avatar.url = avatarUrl;
      }).catch(err => {
        console.log(err)
      });
    },
    async register() {
      await this.registerMethod();
      window.localStorage.setItem("avatar",this.loginForm.avatar.default);
    },
    async registerMethod () {
      await this.getOssPicture();
      //this.loginForm.avatar.url = await ossUpload.getOssPicture(this.loginForm.avatar.file);
      const self = this;
      this.$axios({
        method: 'post',
        url: '/skill/user/userRegister',
        data: {
          username: self.loginForm.username,
          password: self.loginForm.password,
          nickname: self.loginForm.nickname,
          summary: self.loginForm.summary,
          avatar: self.loginForm.avatar.url
      }
      }).then(successResponse => {
        var jsonString = JSON.stringify(successResponse.data);
        var jsonObj = JSON.parse(jsonString);
        if(jsonObj.success) {
          this.$message({
            message: "注册成功",
            type: 'success'
          });
          setTimeout(() => {
            self.$router.push('/userLogin');
          }, 1000)
        } else if (jsonObj.code === 2008) {
          this.$message({
            message: "该账号已存在",
            type: 'warning'
          });
        }
      })

    }
  },
  computed: {
    avatarShow() {
      return window.localStorage.getItem("avatar");}
  }
}
</script>

<style lang="scss" scoped>
@import "../../assets/style/common";
.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 90px auto;
  width: 350px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  .login_title {
    margin: 0 auto 40px auto;
    text-align: center;
    color: #505458;
    }
  .back {
    font-size: 12px;
    cursor: pointer;
    @include fontGradual(#3eb3e5)
  }
  .avatar {
    img {
      margin-left: 140px;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      cursor: pointer;
    }
    input {
    }
    label {
      div {
        margin-left: 95px;
        width: 150px;
        @include btn_add();
      }

    }
  }
}
</style>
